package cn.rtplay.esp32camcar;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Lifecycle;

import com.afollestad.materialdialogs.MaterialDialog;
import com.uber.autodispose.AutoDispose;
import com.uber.autodispose.android.lifecycle.AndroidLifecycleScopeProvider;

import java.io.File;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Objects;

import cn.rtplay.esp32camcar.databinding.StaticLoadBinding;
import cn.rtplay.esp32camcar.toolUtils.LogUtil;
import cn.rtplay.esp32camcar.downloadApk.BGAUpgradeUtil;
import cn.rtplay.esp32camcar.downloadFile.RTBUpgradeUtil;
import cn.rtplay.esp32camcar.rxHttpGet.ConfData;
import cn.rtplay.esp32camcar.rxHttpGet.LoadData;
import cn.rtplay.esp32camcar.rxHttpGet.observers.ProgressObserver;
import cn.rtplay.esp32camcar.rxHttpGet.RxHttp;
import cn.rtplay.esp32camcar.rxHttpGet.RxSchedulers;
import cn.rtplay.esp32camcar.rxHttpGet.VersionData;
import cn.rtplay.esp32camcar.toolUtils.AppVersions;
import cn.rtplay.esp32camcar.toolUtils.ConfUtil;
import cn.rtplay.esp32camcar.toolUtils.NetworkUtils;
import cn.rtplay.esp32camcar.toolUtils.Tools;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;


public class StaticLoad extends Fragment implements EasyPermissions.PermissionCallbacks {
    //读写本地存储权限
    private static final int PERMISSION_READ_WRITE_LOCAL = 1;
    //下载apk文件权限请求码
    private static final int PERMISSION_DOWNLOAD_APK = 2;
    //下载load文件权限请求码
    private static final int PERMISSION_DOWNLOAD_LOAD = 3;
    //下载conf文件权限请求码
    private static final int PERMISSION_DOWNLOAD_CONF = 4;
    //本地定位权限请求码
    private static final int PERMISSION_FINE_LOCATION = 5;
    //开关wifi权限
    private static final int PERMISSION_WIFI_STATE = 6;

    private StaticLoadBinding mViewBinding;

    private MaterialDialog mMaterialDialog;
    protected Context mContext;
    private MaterialDialog mDialog;

    private String mNewVersion = "";
    private String mApkUrl = "https://www.rtplay.cn/esp32car/apk/esp32car_Vxxxx.apk";
    private String mLoadVersion = "";
    private String mLoadUrl = "https://www.rtplay.cn/esp32car/load/xxxx.yyy";
    private String mConfVersion = "";
    private String mConfUrl = "https://www.rtplay.cn/esp32car/conf/xxxx.conf";
    private final String TAG = "StaticLoad";

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        mViewBinding = StaticLoadBinding.inflate(inflater, container, false);
        mContext = mViewBinding.getRoot().getContext();

        stateProcess(SP_REQUEST_WIFI_ENABLE);
        return mViewBinding.getRoot();
    }

    private StaticLoadOnFinishListener mStaticLoadOnFinishListener;

    /**
     * 全部处理完成时的回调
     */
    public interface StaticLoadOnFinishListener {
        void onProcessFinish();
    }

    /**
     * 设置回调接口
     *
     * @param onFinishListener 回调对象
     */
    public void setStaticLoadOnFinishListenerListener(StaticLoadOnFinishListener onFinishListener) {
        this.mStaticLoadOnFinishListener = onFinishListener;
    }

    /**
     * 下载loading文件
     */
    private void downloadLoadFile() {
        LogUtil.v(TAG, "downloadLoadFile: in");
        mViewBinding.progressBarView.setVisibility(View.VISIBLE);
        mViewBinding.downloadName.setVisibility(View.VISIBLE);
        // 下载新版 LOAD 文件
        RTBUpgradeUtil.downloadFile(mLoadUrl, mLoadVersion)
                .as(AutoDispose.autoDisposable(AndroidLifecycleScopeProvider.from(this, Lifecycle.Event.ON_DESTROY)))
                .subscribe(new Observer<File>() {
                    @Override
                    public void onError(Throwable e) {
                        LogUtil.e(TAG, "downloadLoadFile: onError-> " + e.getMessage());
                        stateProcess(SP_GET_LATEST_CONF_VERSION);
                    }

                    @Override
                    public void onComplete() {
                        LogUtil.v(TAG, "downloadLoadFile: onComplete!");
                        RTBUpgradeUtil.setDownloadFileType("mp4", mLoadVersion);
                        AppVersions.getInstance().refreshLocalLoadName(mContext);
                        stateProcess(SP_GET_LATEST_CONF_VERSION);
                    }

                    @Override
                    public void onSubscribe(Disposable d) {
                        LogUtil.v(TAG, "downloadLoadFile: onSubscribe!");
                    }

                    @Override
                    public void onNext(File apkFile) {
                        LogUtil.v(TAG, "downloadLoadFile: onNext!");
                    }
                });
    }

    /**
     * 下载conf文件
     */
    private void downloadConfFile() {
        LogUtil.v(TAG, "downloadConfFile: in");
        mViewBinding.progressBarView.setVisibility(View.VISIBLE);
        mViewBinding.downloadName.setVisibility(View.VISIBLE);
        // 下载新版 conf 文件
        RTBUpgradeUtil.downloadFile(mConfUrl, mConfVersion)
                .as(AutoDispose.autoDisposable(AndroidLifecycleScopeProvider.from(this, Lifecycle.Event.ON_DESTROY)))
                .subscribe(new Observer<File>() {
                    @Override
                    public void onError(Throwable e) {
                        LogUtil.e(TAG, "downloadConfFile: onError-> " + e.getMessage());
                        ConfUtil.getInstance().AnalyseConfFile(mContext);
                        if (mStaticLoadOnFinishListener != null) {
                            mViewBinding.downloadName.setVisibility(View.INVISIBLE);
                            mViewBinding.progressBarView.setVisibility(View.INVISIBLE);
                            mStaticLoadOnFinishListener.onProcessFinish();
                        }

                    }

                    @Override
                    public void onComplete() {
                        LogUtil.v(TAG, "downloadConfFile: onComplete!");
                        ConfUtil.getInstance().AnalyseConfFile(mContext);
                        if (mStaticLoadOnFinishListener != null) {
                            mViewBinding.downloadName.setVisibility(View.INVISIBLE);
                            mViewBinding.progressBarView.setVisibility(View.INVISIBLE);
                            mStaticLoadOnFinishListener.onProcessFinish();
                        }
                    }

                    @Override
                    public void onSubscribe(Disposable d) {
                        LogUtil.v(TAG, "downloadConfFile: onSubscribe!");
                    }

                    @Override
                    public void onNext(File apkFile) {
                        AppVersions.getInstance().refreshLocalConfName(mContext);
                        LogUtil.v(TAG, "downloadConfFile: onNext!");
                    }
                });
    }

    /**
     * 下载新版 apk 文件
     */
    @AfterPermissionGranted(PERMISSION_DOWNLOAD_APK)
    private void downloadApkFile() {
        LogUtil.v(TAG, "downloadApkFile: in");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            // 如果新版 apk 文件已经下载过了，直接 return，此时不需要开发者调用安装 apk 文件的方法，在 isApkFileDownloaded 里已经调用了安装」
            if (BGAUpgradeUtil.isApkFileDownloaded(mNewVersion)) {
                return;
            }
            LogUtil.v(TAG, "downloadApkFile: start");
            // 下载新版 apk 文件
            BGAUpgradeUtil.downloadApkFile(mApkUrl, mNewVersion)
                    .as(AutoDispose.autoDisposable(AndroidLifecycleScopeProvider.from(this, Lifecycle.Event.ON_DESTROY)))
                    .subscribe(new Observer<File>() {
                        @Override
                        public void onError(Throwable e) {
                            dismissDownloadingDialog();
                        }

                        @Override
                        public void onComplete() {
                            dismissDownloadingDialog();
                        }

                        @Override
                        public void onSubscribe(Disposable d) {
                            showDownloadingDialog();
                        }

                        @Override
                        public void onNext(File apkFile) {
                            if (apkFile != null) {
                                BGAUpgradeUtil.completeDownloadAPK(mNewVersion);
                                BGAUpgradeUtil.installApk(mNewVersion);
                                LogUtil.v(TAG, "downloadApkFile: onNext: installApk");
                            }
                        }
                    });
        } else {
            String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
            if (EasyPermissions.hasPermissions(mContext, perms)) {
                // 如果新版 apk 文件已经下载过了，直接 return，此时不需要开发者调用安装 apk 文件的方法，在 isApkFileDownloaded 里已经调用了安装」
                if (BGAUpgradeUtil.isApkFileDownloaded(mNewVersion)) {
                    return;
                }
                LogUtil.v(TAG, "downloadApkFile: start");
                // 下载新版 apk 文件
                BGAUpgradeUtil.downloadApkFile(mApkUrl, mNewVersion)
                        .as(AutoDispose.autoDisposable(AndroidLifecycleScopeProvider.from(this, Lifecycle.Event.ON_DESTROY)))
                        .subscribe(new Observer<File>() {
                            @Override
                            public void onError(Throwable e) {
                                dismissDownloadingDialog();
                            }

                            @Override
                            public void onComplete() {
                                dismissDownloadingDialog();
                            }

                            @Override
                            public void onSubscribe(Disposable d) {
                                showDownloadingDialog();
                            }

                            @Override
                            public void onNext(File apkFile) {
                                if (apkFile != null) {
                                    BGAUpgradeUtil.completeDownloadAPK(mNewVersion);
                                    BGAUpgradeUtil.installApk(mNewVersion);
                                    LogUtil.v(TAG, "downloadApkFile: onNext: installApk");
                                }
                            }
                        });
            } else {
                EasyPermissions.requestPermissions(this, getResources().getString(R.string.external_permissions), PERMISSION_DOWNLOAD_APK, perms);
            }
        }
    }

    /**
     * 显示下载对话框
     */
    private void showDownloadingDialog() {
        if (mMaterialDialog == null) {
            mMaterialDialog = new MaterialDialog.Builder(mContext)
                    .title(getResources().getString(R.string.update))
                    .content(getResources().getString(R.string.updating))
                    .icon(Objects.requireNonNull(ContextCompat.getDrawable(mContext, R.mipmap.ic_launcher)))
                    .canceledOnTouchOutside(false)
                    .progress(false, 100, false)
                    .showListener(dialogInterface -> mDialog = (MaterialDialog) dialogInterface)
                    .show();
            // 监听下载进度
            Disposable apkDis = BGAUpgradeUtil
                    .getDownloadProgressEventObservable()
                    .as(AutoDispose.autoDisposable(AndroidLifecycleScopeProvider.from(this, Lifecycle.Event.ON_DESTROY)))
                    .subscribe(downloadProgressEvent -> {
                        if (mMaterialDialog != null && mMaterialDialog.isShowing() && downloadProgressEvent.isNotDownloadFinished()) {
                            LogUtil.d(TAG, "showDownloadingDialog: setProgress-> " + downloadProgressEvent.getProgress());
                            int setProgress = setProgress(downloadProgressEvent.getProgress(), downloadProgressEvent.getTotal());
                            if (mDialog != null)
                                mDialog.setProgress(setProgress);
                        }
                    });
        }
    }

    /**
     * 隐藏下载对话框
     */
    private void dismissDownloadingDialog() {
        if (mMaterialDialog != null) {
            mMaterialDialog.dismiss();
        }
    }

    /**
     * 根据文件下载大小计算下载百分比
     *
     * @param progress:当前已下载大小
     * @param maxProgress      总大小
     * @return 已下载的百分比
     */
    private int setProgress(long progress, long maxProgress) {
        return (int) (progress * 100 / maxProgress);
    }

    /**
     * 获取本地相关的所有版本号
     */
    @AfterPermissionGranted(PERMISSION_READ_WRITE_LOCAL)
    private void readLocalVersions() {
        LogUtil.v(TAG, "readLocalVersions: in");
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (AppVersions.getInstance().getLocalAPKName(mContext).compareTo(AppVersions.getInstance().getVersionName(mContext)) > 0) {
                BGAUpgradeUtil.isApkFileDownloaded(AppVersions.getInstance().getLocalAPKName(mContext));
            } else if (AppVersions.getInstance().getLocalAPKName(mContext).compareTo(AppVersions.getInstance().getVersionName(mContext)) == 0) {
                BGAUpgradeUtil.deleteOldApk(AppVersions.getInstance().getLocalAPKName(mContext));
            }
            stateProcess(SP_GET_LATEST_APK_VERSION);
        } else {
            String[] perms = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
            if (EasyPermissions.hasPermissions(mContext, perms)) {
                if (AppVersions.getInstance().getLocalAPKName(mContext).compareTo(AppVersions.getInstance().getVersionName(mContext)) > 0) {
                    BGAUpgradeUtil.isApkFileDownloaded(AppVersions.getInstance().getLocalAPKName(mContext));
                } else if (AppVersions.getInstance().getLocalAPKName(mContext).compareTo(AppVersions.getInstance().getVersionName(mContext)) == 0) {
                    BGAUpgradeUtil.deleteOldApk(AppVersions.getInstance().getLocalAPKName(mContext));
                }
                stateProcess(SP_GET_LATEST_APK_VERSION);
            } else {
                EasyPermissions.requestPermissions(this, getResources().getString(R.string.external_permissions), PERMISSION_READ_WRITE_LOCAL, perms);
            }
        }
    }

    /**
     * 获取网络连接状态
     */
    private void getApkUpdate() {
        LogUtil.v(TAG, "getApkUpdate: in");
        int netWorkType = NetworkUtils.getNetWorkType(mContext);
        if (netWorkType == NetworkUtils.NO_NET_WORK) {
            ConfUtil.getInstance().AnalyseConfFile(mContext);
            if (mStaticLoadOnFinishListener != null) {
                mViewBinding.downloadName.setVisibility(View.INVISIBLE);
                mViewBinding.progressBarView.setVisibility(View.INVISIBLE);
                mStaticLoadOnFinishListener.onProcessFinish();
            }
        } else {
            RxHttp.getInstance().getSyncServer().getAPKVersion("version")
                    .compose(RxSchedulers.observableIO2Main(mContext))
                    .as(AutoDispose.autoDisposable(AndroidLifecycleScopeProvider.from(this, Lifecycle.Event.ON_DESTROY)))
                    .subscribe(new ProgressObserver<VersionData>((Activity) mContext) {
                        @Override
                        public void onSuccess(VersionData result) {
                            mNewVersion = result.getMajor() + "." + result.getMinor() + "." + result.getVerision();
                            LogUtil.d(TAG, "getApkUpdate: onSuccess: lastApkVer->" + mNewVersion);
                            mApkUrl = mApkUrl.replaceFirst("xxxx", mNewVersion);
                            LogUtil.d(TAG, "getApkUpdate: onSuccess: mApkUrl->" + mApkUrl);
                            if ((mNewVersion.compareTo(AppVersions.getInstance().getVersionName(mContext)) > 0)
                                    && (mNewVersion.compareTo(AppVersions.getInstance().getLocalAPKName(mContext)) > 0)) {
                                new MaterialDialog.Builder(mContext)
                                        .title(getResources().getString(R.string.update))
                                        .content(result.getContent())
                                        .icon(Objects.requireNonNull(ContextCompat.getDrawable(mContext, R.mipmap.ic_launcher)))
                                        .canceledOnTouchOutside(false)
                                        .positiveText(getResources().getString(R.string.download))
                                        .negativeText(getResources().getString(R.string.cancel))
                                        .onPositive((dialog, which) -> downloadApkFile())
                                        .onNegative((dialog, which) -> stateProcess(SP_GET_LATEST_LOADING_VERSION))
                                        .show();
                            } else {
                                stateProcess(SP_GET_LATEST_LOADING_VERSION);
                            }
                        }

                        @Override
                        public void onFailure(Throwable e, String errorMsg) {
                            LogUtil.e(TAG, "getApkUpdate: onFailure");
                            stateProcess(SP_GET_LATEST_LOADING_VERSION);
                        }
                    });
        }
    }

    /**
     * 获取loading更新
     */
    @AfterPermissionGranted(PERMISSION_DOWNLOAD_LOAD)
    private void getLoadingUpdate() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            // 监听下载进度
            Disposable loadDis = RTBUpgradeUtil
                    .getDownloadProgressEventObservable()
                    .as(AutoDispose.autoDisposable(AndroidLifecycleScopeProvider.from(this, Lifecycle.Event.ON_DESTROY)))
                    .subscribe(rtbDownloadProgressEvent -> {
                        int setProgress = setProgress(rtbDownloadProgressEvent.getProgress(), rtbDownloadProgressEvent.getTotal());
                        mViewBinding.progressBarView.setProgress(setProgress);
                        DecimalFormat max = new DecimalFormat("0.00");
                        DecimalFormat curr = new DecimalFormat("0.00");
                        mViewBinding.downloadName.setText(String.format(getResources().getString(R.string.load_download_description), curr.format(rtbDownloadProgressEvent.getProgress() / 1048576.0), max.format(rtbDownloadProgressEvent.getTotal() / 1048576.0)));
                    });
            //获取load最新版本
            RxHttp.getInstance().getSyncServer().getLoadVersion("load")
                    .compose(RxSchedulers.observableIO2Main(mContext))
                    .as(AutoDispose.autoDisposable(AndroidLifecycleScopeProvider.from(this, Lifecycle.Event.ON_DESTROY)))
                    .subscribe(new ProgressObserver<LoadData>((Activity) mContext) {
                        @Override
                        public void onSuccess(LoadData result) {
                            mLoadVersion = result.getVersion();
                            LogUtil.d(TAG, "getLoadingUpdate: onSuccess: lastLoadVer->" + mLoadVersion);
                            mLoadUrl = mLoadUrl.replaceFirst("xxxx", mLoadVersion);
                            mLoadUrl = mLoadUrl.replaceFirst("yyy", result.getType());
                            LogUtil.d(TAG, "getLoadingUpdate: onSuccess: mLoadUrl->" + mLoadUrl);
                            if (mLoadVersion.compareTo(AppVersions.getInstance().getLocalLoadName(mContext)) > 0) {
                                RTBUpgradeUtil.setDownloadPara("mp4.tmp", "load");
                                downloadLoadFile();
                            } else {
                                stateProcess(SP_GET_LATEST_CONF_VERSION);
                            }
                        }

                        @Override
                        public void onFailure(Throwable e, String errorMsg) {
                            stateProcess(SP_GET_LATEST_CONF_VERSION);
                        }
                    });
        } else {
            String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
            if (EasyPermissions.hasPermissions(mContext, perms)) {
                // 监听下载进度
                Disposable loadDis = RTBUpgradeUtil
                        .getDownloadProgressEventObservable()
                        .as(AutoDispose.autoDisposable(AndroidLifecycleScopeProvider.from(this, Lifecycle.Event.ON_DESTROY)))
                        .subscribe(rtbDownloadProgressEvent -> {
                            int setProgress = setProgress(rtbDownloadProgressEvent.getProgress(), rtbDownloadProgressEvent.getTotal());
                            mViewBinding.progressBarView.setProgress(setProgress);
                            DecimalFormat max = new DecimalFormat("0.00");
                            DecimalFormat curr = new DecimalFormat("0.00");
                            mViewBinding.downloadName.setText(String.format(getResources().getString(R.string.load_download_description), curr.format(rtbDownloadProgressEvent.getProgress() / 1048576.0), max.format(rtbDownloadProgressEvent.getTotal() / 1048576.0)));
                        });
                //获取load最新版本
                RxHttp.getInstance().getSyncServer().getLoadVersion("load")
                        .compose(RxSchedulers.observableIO2Main(mContext))
                        .as(AutoDispose.autoDisposable(AndroidLifecycleScopeProvider.from(this, Lifecycle.Event.ON_DESTROY)))
                        .subscribe(new ProgressObserver<LoadData>((Activity) mContext) {
                            @Override
                            public void onSuccess(LoadData result) {
                                mLoadVersion = result.getVersion();
                                LogUtil.d(TAG, "getLoadingUpdate: onSuccess: lastLoadVer->" + mLoadVersion);
                                mLoadUrl = mLoadUrl.replaceFirst("xxxx", mLoadVersion);
                                mLoadUrl = mLoadUrl.replaceFirst("yyy", result.getType());
                                LogUtil.d(TAG, "getLoadingUpdate: onSuccess: mLoadUrl->" + mLoadUrl);
                                if (mLoadVersion.compareTo(AppVersions.getInstance().getLocalLoadName(mContext)) > 0) {
                                    RTBUpgradeUtil.setDownloadPara("mp4.tmp", "load");
                                    downloadLoadFile();
                                } else {
                                    stateProcess(SP_GET_LATEST_CONF_VERSION);
                                }
                            }

                            @Override
                            public void onFailure(Throwable e, String errorMsg) {
                                stateProcess(SP_GET_LATEST_CONF_VERSION);
                            }
                        });
            } else {
                EasyPermissions.requestPermissions(this, getResources().getString(R.string.external_permissions), PERMISSION_DOWNLOAD_LOAD, perms);
            }
        }
    }

    /**
     * 获取conf更新
     */
    @AfterPermissionGranted(PERMISSION_DOWNLOAD_CONF)
    private void getConfUpdate() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            // 监听下载进度
            Disposable confDis = RTBUpgradeUtil
                    .getDownloadProgressEventObservable()
                    .as(AutoDispose.autoDisposable(AndroidLifecycleScopeProvider.from(this, Lifecycle.Event.ON_DESTROY)))
                    .subscribe(rtbDownloadProgressEvent -> {
                        int setProgress = setProgress(rtbDownloadProgressEvent.getProgress(), rtbDownloadProgressEvent.getTotal());
                        mViewBinding.progressBarView.setProgress(setProgress);
                        DecimalFormat max = new DecimalFormat("0.00");
                        DecimalFormat curr = new DecimalFormat("0.00");
                        mViewBinding.downloadName.setText(String.format(getResources().getString(R.string.conf_download_description), curr.format(rtbDownloadProgressEvent.getProgress() / 1024.0), max.format(rtbDownloadProgressEvent.getTotal() / 1024.0)));
                    });
            //获取conf最新版本
            RxHttp.getInstance().getSyncServer().getConfVersion("conf")
                    .compose(RxSchedulers.observableIO2Main(mContext))
                    .as(AutoDispose.autoDisposable(AndroidLifecycleScopeProvider.from(this, Lifecycle.Event.ON_DESTROY)))
                    .subscribe(new ProgressObserver<ConfData>((Activity) mContext) {
                        @Override
                        public void onSuccess(ConfData result) {
                            mConfVersion = result.getVersion();
                            LogUtil.d(TAG, "getConfUpdate: onSuccess: mConfVersion->" + mConfVersion);
                            mConfUrl = mConfUrl.replaceFirst("xxxx", mConfVersion);
                            LogUtil.d(TAG, "getConfUpdate: onSuccess: mConfUrl->" + mConfUrl);
                            if (mConfVersion.compareTo(AppVersions.getInstance().getLocalConfName(mContext)) > 0) {
                                RTBUpgradeUtil.setDownloadPara("conf", "conf");
                                downloadConfFile();
                            } else {
                                LogUtil.d(TAG, "getConfUpdate: onSuccess: else");
                                ConfUtil.getInstance().AnalyseConfFile(mContext);
                                if (mStaticLoadOnFinishListener != null) {
                                    mViewBinding.downloadName.setVisibility(View.INVISIBLE);
                                    mViewBinding.progressBarView.setVisibility(View.INVISIBLE);
                                    mStaticLoadOnFinishListener.onProcessFinish();
                                }
                            }
                        }

                        @Override
                        public void onFailure(Throwable e, String errorMsg) {
                            LogUtil.e(TAG, "getConfUpdate: onFailure");
                            ConfUtil.getInstance().AnalyseConfFile(mContext);
                            if (mStaticLoadOnFinishListener != null) {
                                mViewBinding.downloadName.setVisibility(View.INVISIBLE);
                                mViewBinding.progressBarView.setVisibility(View.INVISIBLE);
                                mStaticLoadOnFinishListener.onProcessFinish();
                            }
                        }
                    });
        } else {
            String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
            if (EasyPermissions.hasPermissions(mContext, perms)) {
                // 监听下载进度
                Disposable confDis = RTBUpgradeUtil
                        .getDownloadProgressEventObservable()
                        .as(AutoDispose.autoDisposable(AndroidLifecycleScopeProvider.from(this, Lifecycle.Event.ON_DESTROY)))
                        .subscribe(rtbDownloadProgressEvent -> {
                            int setProgress = setProgress(rtbDownloadProgressEvent.getProgress(), rtbDownloadProgressEvent.getTotal());
                            mViewBinding.progressBarView.setProgress(setProgress);
                            DecimalFormat max = new DecimalFormat("0.00");
                            DecimalFormat curr = new DecimalFormat("0.00");
                            mViewBinding.downloadName.setText(String.format(getResources().getString(R.string.conf_download_description), curr.format(rtbDownloadProgressEvent.getProgress() / 1024.0), max.format(rtbDownloadProgressEvent.getTotal() / 1024.0)));
                        });
                //获取conf最新版本
                RxHttp.getInstance().getSyncServer().getConfVersion("conf")
                        .compose(RxSchedulers.observableIO2Main(mContext))
                        .as(AutoDispose.autoDisposable(AndroidLifecycleScopeProvider.from(this, Lifecycle.Event.ON_DESTROY)))
                        .subscribe(new ProgressObserver<ConfData>((Activity) mContext) {
                            @Override
                            public void onSuccess(ConfData result) {
                                mConfVersion = result.getVersion();
                                LogUtil.d(TAG, "getConfUpdate: onSuccess: mConfVersion->" + mConfVersion);
                                mConfUrl = mConfUrl.replaceFirst("xxxx", mConfVersion);
                                LogUtil.d(TAG, "getConfUpdate: onSuccess: mConfUrl->" + mConfUrl);
                                if (mConfVersion.compareTo(AppVersions.getInstance().getLocalConfName(mContext)) > 0) {
                                    RTBUpgradeUtil.setDownloadPara("conf", "conf");
                                    downloadConfFile();
                                } else {
                                    LogUtil.d(TAG, "getConfUpdate: onSuccess: else");
                                    ConfUtil.getInstance().AnalyseConfFile(mContext);
                                    if (mStaticLoadOnFinishListener != null) {
                                        mViewBinding.downloadName.setVisibility(View.INVISIBLE);
                                        mViewBinding.progressBarView.setVisibility(View.INVISIBLE);
                                        mStaticLoadOnFinishListener.onProcessFinish();
                                    }
                                }
                            }

                            @Override
                            public void onFailure(Throwable e, String errorMsg) {
                                LogUtil.e(TAG, "getConfUpdate: onFailure");
                                ConfUtil.getInstance().AnalyseConfFile(mContext);
                                if (mStaticLoadOnFinishListener != null) {
                                    mViewBinding.downloadName.setVisibility(View.INVISIBLE);
                                    mViewBinding.progressBarView.setVisibility(View.INVISIBLE);
                                    mStaticLoadOnFinishListener.onProcessFinish();
                                }
                            }
                        });
            } else {
                EasyPermissions.requestPermissions(this, getResources().getString(R.string.external_permissions), PERMISSION_DOWNLOAD_CONF, perms);
            }
        }
    }

    private static final int SP_REQUEST_WIFI_ENABLE = 0;
    private static final int SP_FINE_LOCATION_PERMISSION = 1;
    private static final int SP_READ_LOCAL_VERSIONS = 2;
    private static final int SP_GET_LATEST_APK_VERSION = 3;
    private static final int SP_GET_LATEST_LOADING_VERSION = 4;
    private static final int SP_GET_LATEST_CONF_VERSION = 5;

    /**
     * 状态切换过程处理
     *
     * @param state 将要触发的过程
     */
    private void stateProcess(int state) {
        switch (state) {
            case SP_REQUEST_WIFI_ENABLE:
                wifiEnable();
                break;
            case SP_FINE_LOCATION_PERMISSION:
                checkFineLocationPermissions();
                break;
            case SP_READ_LOCAL_VERSIONS:
                readLocalVersions();
                break;
            case SP_GET_LATEST_APK_VERSION:
                getApkUpdate();
                break;
            case SP_GET_LATEST_LOADING_VERSION:
                getLoadingUpdate();
                break;
            case SP_GET_LATEST_CONF_VERSION:
                getConfUpdate();
                break;
            default:
                if (mStaticLoadOnFinishListener != null) {
                    ConfUtil.getInstance().AnalyseConfFile(mContext);
                    mViewBinding.downloadName.setVisibility(View.INVISIBLE);
                    mViewBinding.progressBarView.setVisibility(View.INVISIBLE);
                    mStaticLoadOnFinishListener.onProcessFinish();
                }
        }
    }

    //接受系统权限的处理，这里交给EasyPermissions来处理，回调到 EasyPermissions.PermissionCallbacks接口
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        LogUtil.v(TAG, "onRequestPermissionsResult: in");
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        // 请求权限已经被授权
        LogUtil.v(TAG, "onPermissionsGranted: in->" + requestCode + ":" + perms);
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        //如果用户点击永远禁止，这个时候就需要跳到系统设置页面去手动打开了
        LogUtil.v(TAG, "onPermissionsDenied: in");
/*        new AppSettingsDialog
                .Builder((Activity) mContext)
                .setRationale("此功能需要" + "权限，否则无法正常使用，是否打开设置")
                .setPositiveButton("是")
                .setNegativeButton("否")
                .build()
                .show();*/
        new MaterialDialog.Builder(mContext)
                .title(getResources().getString(R.string.no_permission))
                .content(String.format(getString(R.string.no_x_permission), perms))
                .icon(Objects.requireNonNull(ContextCompat.getDrawable(mContext, R.mipmap.ic_launcher)))
                .canceledOnTouchOutside(false)
                .positiveText(getString(R.string.quit))
                .onPositive((dialog, which) -> Tools.exitApp(mContext))
                .show();

    }

    @Override
    public void onStop() {
        super.onStop();
        LogUtil.v(TAG, "onStop: in");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        LogUtil.v(TAG, "onDestroy: in");
    }

    /**
     * 检查权限
     */
    @AfterPermissionGranted(PERMISSION_FINE_LOCATION)
    private void checkFineLocationPermissions() {
        LogUtil.v(TAG, "checkFineLocationPermissions: in");
        String[] perms = {Manifest.permission.ACCESS_FINE_LOCATION};
        if (!EasyPermissions.hasPermissions(mContext, perms)) {
            EasyPermissions.requestPermissions(this, getResources().getString(R.string.fine_location_permissions), PERMISSION_FINE_LOCATION, perms);
        } else {
            stateProcess(SP_READ_LOCAL_VERSIONS);
        }
    }

    ActivityResultLauncher<Intent> intentActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult result) {
            if (NetworkUtils.isWiFiConnected(mContext)) {
                stateProcess(SP_FINE_LOCATION_PERMISSION);
            } else {
                new MaterialDialog.Builder(mContext)
                        .title(getResources().getString(R.string.prompt))
                        .content(R.string.open_wifi)
                        .icon(Objects.requireNonNull(ContextCompat.getDrawable(mContext, R.mipmap.ic_launcher)))
                        .canceledOnTouchOutside(false)
                        .positiveText(getResources().getString(R.string.to_setting))
                        .onPositive((dialog, which) -> {
                            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
                                Intent intent = new Intent(Settings.Panel.ACTION_WIFI);
                                intentActivityResultLauncher.launch(intent);
                            } else {
                                Intent intent = new Intent(Settings.ACTION_WIFI_SETTINGS);
                                startActivity(intent);
                            }
                        })
                        .show();
            }
        }
    });
    private static final int REQUEST_ENABLE_WIFI = 1;

    @AfterPermissionGranted(PERMISSION_WIFI_STATE)
    private void wifiEnable() {
        LogUtil.v(TAG, "wifiEnable: in");
        String[] perms = {Manifest.permission.CHANGE_WIFI_STATE, Manifest.permission.ACCESS_WIFI_STATE};
        if (EasyPermissions.hasPermissions(mContext, perms)) {
            if (!NetworkUtils.isWiFiConnected(mContext)) {
                WifiManager wifiManager;
                // 获取当前apk的WiFi Service
                wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
                if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.Q) {
                    // 调用函数打开/关闭WiFi,status为boolean变量true/false
                    wifiManager.setWifiEnabled(true);
                    stateProcess(SP_FINE_LOCATION_PERMISSION);
                } else {
                    new MaterialDialog.Builder(mContext)
                            .title(getResources().getString(R.string.prompt))
                            .content(R.string.open_wifi)
                            .icon(Objects.requireNonNull(ContextCompat.getDrawable(mContext, R.mipmap.ic_launcher)))
                            .canceledOnTouchOutside(false)
                            .positiveText(getResources().getString(R.string.to_setting))
                            .onPositive((dialog, which) -> {
                                Intent intent = new Intent(Settings.Panel.ACTION_WIFI);
                                intentActivityResultLauncher.launch(intent);
                                // 在intentActivityResultLauncher回调中判断wifi是否打开，并向下进行
                            })
                            .show();
                }
            } else {
                stateProcess(SP_FINE_LOCATION_PERMISSION);
            }
        } else {
            EasyPermissions.requestPermissions(this, getResources().getString(R.string.fine_location_permissions), PERMISSION_WIFI_STATE, perms);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // User chose not to enable Bluetooth.
        if (requestCode == REQUEST_ENABLE_WIFI && resultCode == Activity.RESULT_CANCELED) {
            Tools.exitApp(mContext);
            return;
        } else {
            stateProcess(SP_FINE_LOCATION_PERMISSION);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
